package com.mainelyapps.test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import com.mainelyapps.test.TestItemizedOverlay;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

public class CoordinateLoggerActivity extends MapActivity {
    
	private Context mContext;
	
	private long count = 0;
	
	private ScrollView scrollV;
	private TextView logTV;
	private Button startBtn;
	private Button stopBtn;
	
	private MapView mapV;
	private MyLocationOverlay myLocOverlay;
	private TestItemizedOverlay checkpointOverlays;
	
	private Handler mHandler = new Handler();
	private Runnable mUpdateTimeTask;
	private long mStartTime = 0L;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mContext = this;
        
        scrollV = (ScrollView) findViewById(R.id.scrollView1);
        logTV = (TextView) findViewById(R.id.logWindow);
        mapV = (MapView) findViewById(R.id.mapview);
        startBtn = (Button) findViewById(R.id.start_btn);
        stopBtn = (Button) findViewById(R.id.stop_btn);
        
        mUpdateTimeTask = new Runnable() {
        	   public void run() {
        	     
        	       long delay = 2000;
        	       mHandler.postDelayed(this, delay);

        	       GeoPoint point = myLocOverlay.getMyLocation();
        	       if(point != null){
        	    	   logTV.append("New Location " + count + ": " + point.getLatitudeE6() + ", " + point.getLongitudeE6() + "\n");
        	    	   ++count;
        	    	   
        	    	   OverlayItem oi = new OverlayItem(point, "Point " + count, "");
        	    	   checkpointOverlays.addOverlay(oi);
        	    	   
        	    	   scrollV.scrollBy(0, 60);
       
        	    	   writeLocationToFile(point);
        	    	}
        	   }
        	};
        
        mapV.setSatellite(true);
        mapV.setBuiltInZoomControls(true);
        
        myLocOverlay = new MyLocationOverlay(this, mapV);
        myLocOverlay.runOnFirstFix(new Runnable(){

			public void run() {
				MapController mc = mapV.getController();
				mc.setZoom(16);
				mapV.getController().animateTo(myLocOverlay.getMyLocation());
			}
			
		});
        
        startBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				addTextToTextView(logTV, "Just clicked the start button\n");
				
				// Start Logging Coordinates
				StartLoggingLocations();
			}
        });
        
        stopBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				addTextToTextView(logTV, "Just clicked the stop button\n");
				
				// Stop Logging Coordinates
				StopLoggingLocations();
			}
        });
        
        checkpointOverlays = new TestItemizedOverlay(getResources().getDrawable(R.drawable.poiflag), this);
        List<Overlay> mapOverlays = mapV.getOverlays();
        mapOverlays.add(checkpointOverlays);
        mapV.invalidate();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	addTextToTextView(logTV, "Resuming operation\n");
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    	addTextToTextView(logTV, "Entering background, disabling updates\n");
    	mStartTime = 0L;
    	StopLoggingLocations();
    	
    }
    
    public void StartLoggingLocations(){
    	if(!(myLocOverlay.isMyLocationEnabled())){
    		if(myLocOverlay.enableMyLocation()){
    			List<Overlay> mapOverlays = mapV.getOverlays();
    			
    			mapOverlays.add(myLocOverlay);
    			
    			mapV.invalidate();
    			
    			addTextToTextView(logTV, "Successfully enabled the current location\n");
    			
    			if (mStartTime == 0L) {
    	            mStartTime = System.currentTimeMillis();
    	            mHandler.removeCallbacks(mUpdateTimeTask);
    	            mHandler.postDelayed(mUpdateTimeTask, 100);
    	       }
    		}
    		else{
    			addTextToTextView(logTV, "Failed to enable the current location\n");
    		}
    	}
    }
    
    public void StopLoggingLocations(){
    	if(myLocOverlay.isMyLocationEnabled()){
    		List<Overlay> mapOverlays = mapV.getOverlays();
			
			mapOverlays.remove(myLocOverlay);
			
			mapV.invalidate();
			
    		myLocOverlay.disableMyLocation();
    		
    		mHandler.removeCallbacks(mUpdateTimeTask);
    	}
    }
    
    private void addTextToTextView(TextView tv, CharSequence text){
    	tv.append(text);

    	scrollV.scrollBy(0, 60);
    }

    private void writeLocationToFile(GeoPoint p){
    	try{
    		FileOutputStream fout = openFileOutput("pathcoords.txt", Context.MODE_APPEND);
		
    		String coordStr = Integer.toString(p.getLatitudeE6()) + ", " + Integer.toString(p.getLongitudeE6()) + "\n";
    		fout.write(coordStr.getBytes());
    		fout.close();
    		
    		addTextToTextView(logTV, "Wrote " + coordStr + " to the output file\n");
    		
	 	} catch (FileNotFoundException e) {
	 			// TODO Auto-generated catch block
	 			e.printStackTrace();
	 	} catch (IOException e) {
	 			// TODO Auto-generated catch block
	 			e.printStackTrace();
	 	}
    }
    
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
}